package com.xtayfjpk.dwr.test;

import java.util.Collection;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import org.directwebremoting.Browser;
import org.directwebremoting.ScriptBuffer;
import org.directwebremoting.ScriptSession;

public class MessagePusher {
	
	public void push() {
		Timer timer = new Timer();
		final Random random = new Random();
		timer.scheduleAtFixedRate(new TimerTask() {
			@Override
			public void run() {
				final String content = "x=" + random.nextInt(100) + ",y=" + random.nextInt(100);
				Runnable runnable = new Runnable() {
					private ScriptBuffer script = new ScriptBuffer();
					public void run() {
						Point point = new Point();
						point.setX(random.nextInt(100));
						point.setY(random.nextInt(100));
						// 设置要调用的 js及参数
						script.appendCall("show", content, point);
						// 得到所有ScriptSession
						Collection<ScriptSession> sessions = Browser.getTargetSessions();
						// 遍历每一个ScriptSession
						for (ScriptSession scriptSession : sessions) {
							scriptSession.addScript(script);
						}
					}
				};
				//执行推送
				Browser.withAllSessions(runnable);
				
			}
		}, 0, 2000);
		
		
	}
}
